package com.flower.oss;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author lavender
 * @version 1.0
 * @date 2024-10-22 17:14
 */
public class Demo {

    public static void main(String[] args) {
        System.out.println("\n测试用例4：相同频率");
        ArrayList<String> list = new ArrayList<>();
        list.add("www.b.com");
        list.add("www.b.com");
        list.add("www.b.com");
        list.add("www.a.com");
        list.add("www.a.com");
        list.add("www.c.com");
        list.add("www.c.com");
        list.add("www.c.com");
        list.add("www.c.com");
        list.add("www.z.com");

        System.out.println(findTopTenDomains(list));





    }


    public static List<String> findTopTenDomains(List<String> domains) {
        if (domains == null || domains.isEmpty()) {
            return new ArrayList<>();
        }

        // 使用HashMap统计频率
        Map<String, Integer> frequencyMap = new HashMap<>();
        for (String domain : domains) {
            frequencyMap.put(domain, frequencyMap.getOrDefault(domain, 0) + 1);
        }

        System.out.println(frequencyMap.toString());

        // 转换为List并排序
        return frequencyMap.entrySet()
                .stream()
                .sorted((a, b) -> {
                    // 首先按频率降序
                    int compare = b.getValue().compareTo(a.getValue());
                    // 频率相同时按域名字典序
                    if (compare == 0) {
                        return a.getKey().compareTo(b.getKey());
                    }
                    return compare;
                })
                .map(Map.Entry::getKey)
                .limit(10)
                .collect(Collectors.toList());
    }
}
